#!/usr/bin/env python
"""
Module nipu.
For evaluate single-strandness by using NIPU index.
Reference: PLOS Comp. Biology 2008.
"""

import tempfile
import os

###############################################################################

PROGRAM_NAME = "ComputePUvaluesSlidingWindows.pl" 
WINDOW = 30

###############################################################################

def calc_NIPU(seq, mlen=6, outfile=None):
    """
    Calculate PU values for given seq.
    Assuming two scripts exists.
    """
    fd, pufile = tempfile.mkstemp()

    f_program = os.path.join(os.path.dirname(__file__), 'executable', PROGRAM_NAME)
    # calculate
    command = ("perl %s -s %s -m %d -H ./ > %s" % (
        f_program, seq.replace('U', 'T'), mlen, pufile))
    os.system(command)

    # plot figure to outfile
    if outfile:
        os.system("perl %s %s %s" % (
            os.path.join(os.path.dirname(__file__), 'executable', 'plotline.pl'),
            pufile, outfile))

    lines = [line.rstrip() for line in open(pufile).readlines()]
    assert len(lines) == 1, """PU file not generated successfully. 
        Ensure the Root of Vienna package is set correctly in file %s.
    """ % f_program # ensure only one line.

    puvalue = float(lines[0].split()[1]) # position value motif
    os.unlink(pufile)

    return puvalue

###############################################################################
